import sys
from datetime import datetime
from threading import Timer
from event_manager import Event, EventManager

# 事件主题: 新文章
EVENT_TOPIC_ARTICAL = "Event_Topic_Artical"


class PublicAccounts:
    # 事件源 公众号
    def __init__(self, eventManager):
        self.__eventManager = eventManager

    def WriteNewArtical(self):
        # 事件对象，写了新文章
        event = Event(eventTopic=EVENT_TOPIC_ARTICAL)
        event.dict["artical"] = u'如何写出更优雅的代码\n'

        # 发送事件
        self.__eventManager.SendEvent(event)
        print(u'公众号发送新文章\n')


class Listener:
    # 监听器 订阅者
    def __init__(self, username):
        self.__username = username

    # 监听器的处理函数 读文章
    def ReadArtical(self, event):
        print(u'%s 收到新文章' % self.__username)
        print(u'正在阅读新文章内容:%s' % event.dict["artical"])


def test():
    # 实例化监听器
    listener1 = Listener("thinkroom")  # 订阅者1
    listener2 = Listener("steve")     # 订阅者2

    # 实例化事件操作函数
    eventManager = EventManager()

    # 绑定事件和监听器响应函数(新文章)
    eventManager.AddEventListener(EVENT_TOPIC_ARTICAL, listener1.ReadArtical)
    eventManager.AddEventListener(EVENT_TOPIC_ARTICAL, listener2.ReadArtical)

    # 启动事件管理器，启动事件处理线程
    eventManager.Start()

    publicAcc = PublicAccounts(eventManager)
    timer = Timer(2, publicAcc.WriteNewArtical)
    timer.start()


if __name__ == "__main__":
    test()
